﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Linq;
using System.Text;
using JKF.BusinessLayer.BLL;
using JKF.DataModule;
using JKF.DataModule.SqlServerDAL;
using JKF.Entities.Model;
using JKF.Substructure;

namespace JKF.BusinessLayer.BLL
{
    public partial class bllPOINT_LOG
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="searchItem"></param>
        /// <param name="matchWay"></param>
        /// <param name="keyword"></param>
        /// <param name="minPoint"></param>
        /// <param name="maxPoint"></param>
        /// <param name="pageCurrent"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="rowCount"></param>
        /// <returns></returns>
        public DataTable PointSearch(string searchItem, string matchWay, string keyword, string minPoint, string maxPoint, string ownShop,
int pageCurrent, int pageSize, ref int pageCount, ref int rowCount)
        {
            dalPOINT_LOG pointLog = new dalPOINT_LOG();
           // string shopCode = bllSYS_USER.CurrentUser.SHOP_CODE;
            string userKey = bllSYS_USER.CurrentUser.USER_KEY.ToString();
            return pointLog.PointSearch(searchItem, matchWay, keyword, minPoint, maxPoint, ownShop, userKey, pageCurrent, pageSize, ref pageCount, ref rowCount);
        }

        /// <summary>
        /// 查询某人积分日志
        /// </summary>
        /// <param name="customerKey"></param>
        /// <returns></returns>
        public DataSet GetPointLogByPerson(string customerKey)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append(" SELECT  A.POINT_KEY,A.CUSTOMER_KEY, D.NAME AS PONT_TYPE,A.WAY, A.POINT_TIME,  A.POINT_VALUE, A.MEMO,B.CARD_NO, B.MOBILE, B.NAME, C.ACCOUNT"
                          + " FROM   POINT_LOG A "
                          + " INNER JOIN dbo.CUSTOMER B ON A.CUSTOMER_KEY = B.CUSTOMER_KEY  "
                          + " LEFT JOIN dbo.SYS_USER C ON A.USER_CREATE=C.USER_KEY "
                          + " LEFT JOIN dbo.DIC_POINT D ON A.CODE=D.CODE ");
            strSql.Append("   WHERE 1=1 and A.STATUS=1 and A.CUSTOMER_KEY=@CUSTOMER_KEY  ORDER BY POINT_TIME DESC ");
            var dbClass = DB.HR;
            DbCommand dbCommand = dbClass.GetSqlStringCommand(strSql.ToString());
            dbClass.AddInParameter(dbCommand, "CUSTOMER_KEY", DbType.Guid, new Guid(customerKey));

            return dbClass.ExecuteDataSet(dbCommand);
        }

        /// <summary>
        /// 删除积分日志
        /// </summary>
        /// <param name="pointKey"></param>
        /// <returns></returns>
        public bool DeletePointLog(string pointKey)
        {
            var dbClass = DB.HR;
            var cmdList = new List<DbCommand>();
            string logContent = "";

            try
            {
                var strSql = "SELECT CUSTOMER_KEY FROM  POINT_LOG WHERE POINT_KEY=@POINT_KEY";

                var cmd = dbClass.GetSqlStringCommand(strSql);
                dbClass.AddInParameter(cmd, "POINT_KEY", DbType.Guid, new Guid(pointKey));
                object customerKey = dbClass.ExecuteScalar(cmd);


                DataRow tmpRow = bllPOINT_EXCHANGE.GetCustomerByKey(customerKey.ToString());
                logContent = string.Format("删除积分日志，顾客姓名\"{0}\"  手机号\"{1}\":", tmpRow["NAME"].ToString(), tmpRow["MOBILE"].ToString());

                //先删除兑换明细
                const string sql_POINT_LOG_update = "UPDATE  POINT_LOG SET STATUS=9,DATE_UPDATE=GETDATE() WHERE POINT_KEY=@POINT_KEY";
                var POINT_LOG_update_Cmd = dbClass.GetSqlStringCommand(sql_POINT_LOG_update);
                dbClass.AddInParameter(POINT_LOG_update_Cmd, "POINT_KEY", DbType.Guid, new Guid(pointKey));
                cmdList.Add(POINT_LOG_update_Cmd);

                string sql_recover_point = "UPDATE CUSTOMER  "
                + " SET GIVE_POINTS=GIVE_POINTS+isnull((SELECT DEDUCT_POINT "
                + " FROM dbo.POINT_LOG "
                + " WHERE POINT_KEY=@POINT_KEY AND STATUS='1'),0) "
                + " WHERE CUSTOMER_KEY=@CUSTOMER_KEY";
                var recover_point_cmd = dbClass.GetSqlStringCommand(sql_recover_point);
                dbClass.AddInParameter(recover_point_cmd, "CUSTOMER_KEY", DbType.Guid, new Guid(customerKey.ToString()));
                dbClass.AddInParameter(recover_point_cmd, "POINT_KEY", DbType.Guid, new Guid(pointKey));
                cmdList.Add(recover_point_cmd);

                bllSYS_LOG.SaveLog("004001002", "POINT_LOG", pointKey,logContent, "删除", BusinessBase.ClientIp);

                ExecTransaction.Exec(cmdList);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 添加/修改积分日志
        /// </summary>
        /// <param name="pointLogInfo"></param>
        /// <returns></returns>
        public string EditOrInsertPointLog(POINT_LOGinfo pointLogInfo)
        {
            var dal = new dalPOINT_LOG();
            string poinst_key = pointLogInfo.POINT_KEY.ToString();
            string logContent = "";
            DataRow tmpRow = bllPOINT_EXCHANGE.GetCustomerByKey(pointLogInfo.CUSTOMER_KEY.ToString());
            if (!string.IsNullOrEmpty(pointLogInfo.POINT_KEY.ToString()) && poinst_key != "00000000-0000-0000-0000-000000000000")
            {
                var tmodule = dal.GetModel(pointLogInfo.POINT_KEY);
                if (tmodule == null) throw new Exception("数据不存在.");

                pointLogInfo.POINT_KEY = tmodule.POINT_KEY;
                pointLogInfo.DATE_UPDATE = DateTime.Now;
                dal.Update(pointLogInfo);
                dal = null;
           
                if (tmpRow != null)
                {
                    logContent = string.Format("修改积分日志，顾客姓名\"{0}\"  手机号\"{1}\":", tmpRow["NAME"].ToString(), tmpRow["MOBILE"].ToString());
                    if (tmodule.POINT_VALUE != pointLogInfo.POINT_VALUE)
                    {
                        logContent += string.Format("积分值由{0}改为{1};", tmodule.POINT_VALUE, pointLogInfo.POINT_VALUE);
                    }

                    if (tmodule.WAY != pointLogInfo.WAY)
                    {
                        logContent += string.Format("积分方式由{0}改为{1}", tmodule.WAY == "01" ? "消费积分" : "赠送积分", pointLogInfo.WAY == "01" ? "消费积分" : "赠送积分");
                    }

                    bllSYS_LOG.SaveLog("004001002", "POINT_LOG", pointLogInfo.POINT_KEY.ToString(), logContent, "修改", BusinessBase.ClientIp);
                }
            }
            else
            {
                pointLogInfo.POINT_KEY =new Guid(DB.GetNewGuid(DB.HR));
                pointLogInfo.DATE_CREATE = DateTime.Now;
                pointLogInfo.DATE_UPDATE = DateTime.Now;
                pointLogInfo.USER_CREATE = bllSYS_USER.CurrentUser.USER_KEY;
                pointLogInfo.SHOP_CODE = bllSYS_USER.CurrentUser.SHOP_CODE;
                pointLogInfo.STATUS = "1";
                dal.Add(pointLogInfo);
                dal = null;

                bool isSucess = AddPoint(pointLogInfo.CUSTOMER_KEY.ToString(), pointLogInfo.POINT_VALUE, pointLogInfo.CODE);
                if (tmpRow != null)
                {
                    logContent = string.Format("添加积分日志，顾客姓名\"{0}\"  手机号\"{1}\":", tmpRow["NAME"].ToString(), tmpRow["MOBILE"].ToString());
                    bllSYS_LOG.SaveLog("004001002", "POINT_LOG", pointLogInfo.POINT_KEY.ToString(), logContent, "添加", BusinessBase.ClientIp);
                }
            }
            return pointLogInfo.POINT_KEY.ToString();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="CUSTOMER_KEY">顾客key</param>
        /// <param name="POINT_VALUE">添加多少积分（可为负数）</param>
        /// <param name="pointType">01消费积分  02赠送积分</param>
        private bool AddPoint(string CUSTOMER_KEY,int? POINT_VALUE,string pointType)
        {
            var dbClass = DB.HR;
            var cmdList = new List<DbCommand>();
            string sqlText = "";
            try
            {
                if (pointType == "01")
                    sqlText = "UPDATE dbo.CUSTOMER"
                    + " SET GIVE_POINTS=CASE WHEN  CONSUME_POINTS+@POINT_VALUE<0 THEN 0  ELSE  CONSUME_POINTS+@POINT_VALUE END "
                    + " WHERE CUSTOMER_KEY=@CUSTOMER_KEY";
                else
                    sqlText = "UPDATE dbo.CUSTOMER"
                     + " SET GIVE_POINTS=CASE WHEN  GIVE_POINTS+@POINT_VALUE<0 THEN 0  ELSE  GIVE_POINTS+@POINT_VALUE END "
                     + " WHERE CUSTOMER_KEY=@CUSTOMER_KEY";
                var update_point_cmd = dbClass.GetSqlStringCommand(sqlText);
                dbClass.AddInParameter(update_point_cmd, "@CUSTOMER_KEY", DbType.Guid, new Guid(CUSTOMER_KEY.ToString()));
                dbClass.AddInParameter(update_point_cmd, "@POINT_VALUE", DbType.Int16, POINT_VALUE == null ? 0 : POINT_VALUE);
                cmdList.Add(update_point_cmd);

                ExecTransaction.Exec(cmdList);
                return true;
            }
            catch
            {
                return false;
            }

        }
    }
}
